/**
 *	客户端处理
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2024-09-09
 */

package com.framerock.server;

import com.framerock.baselib.CLog;
import com.framerock.baselib.Json;
import com.framerock.baselib.REIM;
import com.framerock.baselib.Rock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class WebSocketClient {

    //定义记录所有客户端信息
    public static Map<String, WebSocketClients> WebSocketsAll = new HashMap<String, WebSocketClients>();

    /**
     * 发送消息
     * */
    public static String send(Map<String,String> da)
    {
        String atype    = Rock.getMapString(da, "atype");
        String receid   = Rock.getMapString(da, "receid");
        String from     = Rock.getMapString(da, "from");
        String bstr     = "";
        if(Rock.isEmpt(receid) || Rock.isEmpt(from))return bstr;


        if(Rock.equals(atype, "send")){
            da.remove("receid");
            getFromClient(from).send(receid, Json.getJsonString(da));
        }

        if(Rock.equals(atype, "getonline")){
            bstr = getFromClient(from).getOnlineUser();
        }

        return bstr;
    }

    /**
     * 用url推送过来的数据 http://地址/reim/push
     * */
    public static String push(String str)
    {
        Map<String,String> da = Json.getJsonObject(str);
        return send(da);
    }

    /**
     * 客户端发来消息处理
     * */
    public static void message(String str, HttpWebSocket ws)
    {
        CLog.debug("message:"+str);
    }

    /**
     * 关闭链接
     * */
    public static void close(HttpWebSocket ws)
    {
        WebSocketClients wcs = getFromClient(ws.from);
        HttpWebSocket ows    = wcs.getClient(ws.adminid);
        if(ows != null) {
            wcs.removeClient(ws.adminid);
            CLog.debug("client("+ws.from+"_"+ws.adminid+":" + ws.sendname + ") close");
        }
    }

    /**
     * 有客户端链接成功
     * */
    public static void addClient(HttpWebSocket ws)
    {
        String info          = ""+ws.from+"_"+ws.adminid+":"+ws.sendname+"";
        WebSocketClients wcs = getFromClient(ws.from);
        HttpWebSocket ows    = wcs.getClient(ws.adminid);
        if(ows != null){
            ows.sendData("offoline");
            ows.close(); //关闭原来的
            CLog.error("client("+info+") exist close");
        }
        wcs.addClient(ws.adminid, ws);
        CLog.debug("client("+info+") connect");
    }

    /**
     * 获取链接客户端
     * */
    public static HttpWebSocket getClient(String from, String adminid)
    {
        WebSocketClients wcs = getFromClient(from);
        return wcs.getClient(adminid);
    }

    /**
     * 获取链接客户端聚合
     * */
    public static WebSocketClients getFromClient(String from)
    {
        WebSocketClients wcs = WebSocketsAll.get(from);
        if(wcs == null){
            wcs = new WebSocketClients(from);
            WebSocketsAll.put(from, wcs);
        }
        return wcs;
    }

    /**
     * 关闭所有客户端
     * */
    public static void closeAll()
    {

    }

}
